import { EventDispatcher } from "../../event";
import { Injector } from "../injector/Injector";

export abstract class InjectableObject {
    protected _injector: Injector = null;
    protected _dispatcher: EventDispatcher = null;

    public get injector(): Injector {
        if (this._injector == null) {
            this._injector = Injector.default;
        }

        return this._injector;
    }

    public set injector(value: Injector) {
        this._injector = value;
    }

    public forkInjector(): Injector {
        let ret = this.injector.fork();
        this._injector = ret;
        return ret;
    }

    constructor(...args: any[]) {
        this.initialize(...args);
    }

    public initialize(...args: any[]): void {

    }

    public dispose(): void {

    }

    public dispatch(event: string, ...args: unknown[]) {
        let eventDispatcher = this.injector.getInstance(EventDispatcher);
        if (eventDispatcher) {
            eventDispatcher.emit(event, ...args);
        }
    }

    public get dispatcher(): EventDispatcher {
        if (!this._dispatcher) {
            this._dispatcher = this.injector.getInstance(EventDispatcher);
        }
        return this._dispatcher;
    }

}